/**
 * 
 */
package info.niwota.start;

import info.niwota.start.app.AppLoader;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * @author qiangli
 * 
 */
public class BootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context ctx, Intent intent) {
		if (intent.getAction() != null) {
			if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
				StartActivity.ensureRunning(ctx);
				try {
					startup(ctx);
				} catch (Exception e) {
					if (Debug.DEBUG) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * start activities in Startup user folder
	 * 
	 * @param ctx
	 */
	private void startup(Context ctx) {
		List<ResourceInfo> list = AppLoader.loadStartup(ctx);
		
		int c = (list == null ? 0 : list.size());
		for (int i = 0; i < c; i++) {
			ResourceInfo ri = list.get(i);
			Intent in = ri.getIntent();
			try {
				in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				in.putExtra("extra.startup", true);
				ctx.startActivity(in);
			} catch (Exception e) {
				if (Debug.DEBUG) {
					e.printStackTrace();
				}
			}
		}
	}
}
